<template>
  <div v-loading="resultObj.loading">
    <el-card shadow="never">
      <div class="mt-10">
        <p>
          <span>用户的 </span>
          <span style="font-size: 16px; color: #e64004">
            {{ resultObj.distributionInfo.username }}（ID：{{ resultObj.distributionInfo.user_id }}）
          </span>
          <span>分销联盟收益情况</span>
        </p>
      </div>
      <el-divider />
      <div class="tc-main mt-0">
        <div class="item">
          <img src="@/assets/houtai_2_05.png" alt="" class="image" />
          <div class="info">
            <p>
              <span><span class="m">$</span>{{ resultObj.distributionInfo.order_amount }}</span>
            </p>
            <p>分销总充值</p>
          </div>
        </div>
        <div class="item">
          <img src="@/assets/houtai_2_07.png" alt="" class="image" />
          <div class="info">
            <p>
              <span><span class="m">$</span>{{ resultObj.distributionInfo.total_income }}</span>
              <span class="el-badge mark">
                <sup class="el-badge__content">{{ resultObj.distributionInfo.income_ratio }}</sup>
              </span>
            </p>
            <p>总佣金</p>
          </div>
        </div>
        <div class="item">
          <img src="@/assets/houtai_2_08.png" alt="" class="image" />
          <div class="info">
            <p>
              <span><span class="m">$</span>{{ resultObj.distributionInfo.income }}</span>
            </p>
            <p>待结算佣金</p>
          </div>
        </div>
        <div class="item">
          <img src="@/assets/houtai_2_09.png" alt="" class="image" />
          <div class="info">
            <p>
              <span><span class="m">$</span>{{ resultObj.distributionInfo.pay_income }}</span>
            </p>
            <p>已结算佣金</p>
          </div>
        </div>
      </div>
      <el-divider />
      <div>
        <p>
          <span
            >以上所有分销联盟佣金结算，请先联系客服沟通，再申请结算佣金。最低结算佣金$100，低于该金额无法提现，每月申请时间15号。客户联系方式：</span
          >
          <a href="https://t.me/IPXProxyService" target="_blank" class="el-link el-link--primary is-underline" style="margin-right: 10px">
            <span class="el-link--inner">Telegram客服</span>
          </a>
          <a href="https://email.ipxproxy.com/" target="_blank" class="el-link el-link--primary is-underline">
            <span class="el-link--inner" style="margin-right: 10px">Email客服</span>
          </a>
        </p>
      </div>
      <div class="mt-20">
        <el-tabs v-model="currentSubTab" type="card" class="j-tabs" @tab-change="onSubTabChange">
          <el-tab-pane name="1-1" label="邀请信息">
            <template #label>
              <h6 style="font-size: 14px; line-height: 40px">邀请信息</h6>
            </template>
            <el-table :data="resultObj.distributionInviteData" border stripe style="width: 100%" class="j-table mt-0">
              <el-table-column prop="id" label="用户ID" />
              <el-table-column prop="username" label="用户名称" />
              <el-table-column prop="created_at" label="注册时间">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.created_at) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="order_amount" label="充值金额">
                <template #default="scope">
                  <span>${{ scope.row.order_amount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="income" label="获得佣金">
                <template #default="scope">
                  <span>${{ scope.row.income }}</span>
                </template>
              </el-table-column>
            </el-table>
            <div class="j-pagination">
              <el-pagination
                background
                layout="prev, pager, next"
                :current-page="resultObj.distributionInvitePage"
                :pageSize="resultObj.distributionInviteLimit"
                :total="resultObj.distributionInviteTotal"
                @current-change="
                  (val) => {
                    onCurrentChange('distributionInvite', val);
                  }
                "
              />
            </div>
          </el-tab-pane>
          <el-tab-pane name="1-2" label="结算信息">
            <template #label>
              <h6 style="font-size: 14px; line-height: 40px">结算信息</h6>
            </template>
            <el-table :data="resultObj.distributionPayoffData" border stripe style="width: 100%" class="j-table mt-0">
              <el-table-column prop="created_at" label="结算时间">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.created_at) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="id" label="用户ID" />
              <el-table-column prop="username" label="用户名称" />
              <el-table-column prop="income" label="结算佣金" />
              <el-table-column prop="remark" label="备注说明" />
            </el-table>
            <div class="j-pagination">
              <el-pagination
                background
                layout="prev, pager, next"
                :current-page="resultObj.distributionPayoffPage"
                :pageSize="resultObj.distributionPayoffLimit"
                :total="resultObj.distributionPayoffTotal"
                @current-change="
                  (val) => {
                    onCurrentChange('distributionPayoff', val);
                  }
                "
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 编辑 -->
    <Edit ref="editRef" @confirm="onConfirm" />

    <!-- 结算 -->
    <Settlement ref="settlementRef" @confirm="onConfirm" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { setLang } from '@/i18n';
  import { useI18n } from 'vue-i18n';
  import { distributionInfoApi, distributionPayoffApi, distributionInviteApi, distributionUserApi, distributionStatusApi, distributionCannelApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import dayjs from 'dayjs';
  import Edit from '../components/edit.vue';
  import Settlement from '../components/settlement.vue';
import { Card } from 'vant';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const emits = defineEmits<{
    (event: 'confirm'): void;
  }>();

  const currentTab = ref('1');
  const currentSubTab = ref('1-1');

  const editRef = ref();
  const settlementRef = ref();

  const onTabChange = (val) => {
    if (val == '1') {
      onSubTabChange(currentSubTab.value);
    } else if (val == '2') {
      onCurrentChange('distributionUser', 1);
    } else if (val == '3') {
      onCurrentChange('distributionCannel', 1);
    }
  };

  const onSubTabChange = (val) => {
    if (val == '1-1') {
      onCurrentChange('distributionInvite', 1);
    } else if (val == '1-2') {
      onCurrentChange('distributionPayoff', 1);
    }
  };

  const resultObj = reactive({
    distributionInfo: {
      user_id: '',
      username: '',
      total_income: 0,
      income: 0,
      pay_income: 0,
      order_amount: 0,
      income_ratio: '',
    },
    distributionPayoffData: [],
    distributionInviteData: [],
    distributionUserData: [],
    distributionCannelData: [],
    distributionPayoffLimit: 20,
    distributionPayoffPage: 1,
    distributionPayoffTotal: 0,
    distributionInviteLimit: 20,
    distributionInvitePage: 1,
    distributionInviteTotal: 0,
    distributionUserLimit: 20,
    distributionUserPage: 1,
    distributionUserTotal: 0,
    distributionCannelLimit: 20,
    distributionCannelPage: 1,
    distributionCannelTotal: 0,
    loading: false,
    currentTab: '',
  });

  const getDistributionInfo = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionInfo = {};
    distributionInfoApi({})
      .then((res) => {
        if (res.data) {
          resultObj.distributionInfo = res.data;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionInvite = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionInviteData = [];
    distributionInviteApi({
      limit: resultObj.distributionInviteLimit,
      page: resultObj.distributionInvitePage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionInviteData = res.data.list;
          resultObj.distributionInviteTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionPayoff = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionPayoffData = [];
    distributionPayoffApi({
      limit: resultObj.distributionPayoffLimit,
      page: resultObj.distributionPayoffPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionPayoffData = res.data.list;
          resultObj.distributionPayoffTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionUser = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionUserData = [];
    distributionUserApi({
      limit: resultObj.distributionUserLimit,
      page: resultObj.distributionUserPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionUserData = res.data.list;
          resultObj.distributionUserTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const getDistributionCannel = async () => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    resultObj.distributionCannelData = [];
    distributionCannelApi({
      limit: resultObj.distributionCannelLimit,
      page: resultObj.distributionCannelPage,
    })
      .then((res) => {
        if (res.data) {
          resultObj.distributionCannelData = res.data.list;
          resultObj.distributionCannelTotal = res.data.count;
        }
        resultObj.loading = false;
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const onCurrentChange = (type, val) => {
    if (type == 'distributionInvite') {
      resultObj.distributionInvitePage = val;
      getDistributionInvite();
    } else if (type == 'distributionPayoff') {
      resultObj.distributionPayoffPage = val;
      getDistributionPayoff();
    } else if (type == 'distributionUser') {
      resultObj.distributionUserPage = val;
      getDistributionUser();
    } else if (type == 'distributionCannel') {
      resultObj.distributionCannelPage = val;
      getDistributionCannel();
    }
  };

  const onDisChange = (row) => {
    ElMessageBox.confirm('您确定改变该用户的分销功能状态吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        onDisChangeFn(row);
      })
      .catch(() => {});
  };

  const onDisChangeFn = async (row) => {
    // if (resultObj.loading) return false;
    resultObj.loading = true;
    distributionStatusApi({ user_id: row.user_id })
      .then((res) => {
        resultObj.loading = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          getDistributionUser();
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        resultObj.loading = false;
        ElMessage.error(err.message);
      });
  };

  const parseTime = (val: string) => {
    return val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '';
  };

  const onAdd = async (row) => {
    editRef.value.onOpen(row, 'add');
  };

  const onEdit = async (row) => {
    editRef.value.onOpen(row, 'edit');
  };

  const onSettlement = async (row) => {
    settlementRef.value.onOpen(row);
  };

  const onConfirm = () => {
    getDistributionUser();
  };

  onMounted(() => {
    resultObj.distributionInvitePage = 1;
    getDistributionInfo();
    getDistributionInvite();
  });
</script>

<style scoped lang="scss"></style>
